/*
 * @Copyright: 2017 www.yyfax.com Inc. All rights reserved.
 */
package com.yyfax.pay.order.controller.api;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.RedirectView;

import com.yyfax.commons.lang.BeanUtil;
import com.yyfax.commons.lang.DateUtil;
import com.yyfax.pay.common.constants.PayConstants;
import com.yyfax.pay.common.enums.PayRspCodeEnum;
import com.yyfax.pay.common.enums.PaymentEnum;
import com.yyfax.pay.common.enums.QueryTaskTypeEnum;
import com.yyfax.pay.common.model.to.YYPayApiReq;
import com.yyfax.pay.common.util.CommonIdUtils;
import com.yyfax.pay.config.data.service.MerchantConfigService;
import com.yyfax.pay.config.model.po.MerchantConfigPO;
import com.yyfax.pay.order.data.service.PayOrderService;
import com.yyfax.pay.order.model.to.pay.PayOderReturnDataParams;
import com.yyfax.pay.order.model.vo.PayBusiIdVO;
import com.yyfax.pay.order.model.vo.PayOrderVO;
import com.yyfax.pay.order.service.AdapterService;
import com.yyfax.pay.order.service.PayCommonService;
import com.yyfax.pay.third.model.to.yyfax.OrderReturnContent;
import com.yyfax.pay.third.service.ThirdPayService;

/**
 * 支付结果通知<br>
 * 包含：同步通知，异步通知
 * 
 * @author buyi
 * @date 2017-04-12 20:23:19
 * @since v1.0.0
 */
@Controller
public class PayResultReturnController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private AdapterService adapterService;

	@Autowired
	private PayOrderService payOrderService;

	@Autowired
	private MerchantConfigService merchantConfigService;

	@Autowired
	private PayCommonService payCommonService;

	@Autowired
	private PayConstants payConstants;

	/**
	 * 支付同步回调入口
	 * 
	 * @author buyi
	 * @date 2017-04-12 21:00:59
	 * @since v1.0.0
	 * @param payment
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/api/result/pay/return/{payment}")
	public RedirectView orderReturn(@PathVariable("payment") String payment, HttpServletRequest request) throws Exception {
		PaymentEnum paymentEnum = PaymentEnum.fromValue(payment);
		if (payment == null) {
			return null;
		}

		ThirdPayService adapter = adapterService.adapterPayService(paymentEnum);
		// 1.确认签名,确认订单;
		OrderReturnContent returnContent = adapter.transformPayOrderReturn(request);

		if (returnContent == null || !PayRspCodeEnum.SUCCESS.isValue(returnContent.getResultCode())) {// 验签失败
			return null;
		}

		// 2.获取回显地址返回
		PayBusiIdVO payOrderIdVO = CommonIdUtils.getPayBusiIdVo(returnContent.getPayOrderId());

		PayOrderVO payOrderVO = payOrderService.queryPayOrderVOByOrderId(payOrderIdVO.getOrderId(), payOrderIdVO.getMerchantCode());

		// TODO 如果金额不一致，发出预警
		if (!payOrderVO.getAmount().equals(returnContent.getAmount())) {
			logger.error("支付金额：" + payOrderVO.getAmount() + "，同步回调金额：" + returnContent.getAmount() + "不一致");
		}

		// 如果订单交易超时，或者订单状态为处理中，则生成主动查询任务
		if (PayRspCodeEnum.PAY_CODE_REQ_TIME_OUT.isValue(returnContent.getResultCode())
				|| PayRspCodeEnum.PAY_CODE_DEALING.isValue(returnContent.getResultCode())
				|| PayRspCodeEnum.SUCCESS.isValue(returnContent.getResultCode())) {

			try {
				String startTime = DateUtil.datetime2Str(DateUtil.addMinute(new Date(), payConstants.getPayQueryMinuteDelay()));
				payCommonService.saveQueryTask(payOrderVO.getMerchantCode(), payOrderVO.getOrderId(), payOrderVO.getSerialNo(), QueryTaskTypeEnum.PAY,
						payOrderVO.getPayOrderId(), payOrderVO.getPayOrderExtPO().getActPaymentCode(), startTime, null,
						payConstants.getQueryTaskMax(), "");

			} catch (Exception e) {
				logger.error("插入主动查询任务失败,payOrderId" + payOrderVO.getPayOrderId(), e);
			}
		}

		// 获取商户信息
		MerchantConfigPO merchantConfigPO = merchantConfigService.queryByMerchantCode(payOrderIdVO.getMerchantCode());

		PayOderReturnDataParams returnData = new PayOderReturnDataParams();
		returnData.setResultCode(returnContent.getResultCode());
		returnData.setResultMsg(returnContent.getResultMsg());
		returnData.setMerchantCode(payOrderVO.getMerchantCode());
		returnData.setOrderId(payOrderVO.getOrderId());
		returnData.setAmount(payOrderVO.getAmount());

		YYPayApiReq<PayOderReturnDataParams> req = new YYPayApiReq<>();
		req.setSign(returnData.sign(merchantConfigPO.getSignKey()));
		req.setParams(returnData);
		// returnParams.setSign(returnParams.sign(merchantConfigPO.getSignKey()));

		String url = payOrderVO.getReturnUrl();
		logger.info("同步回调成功，响应参数url:{},data:{}", url, req);

		RedirectView view = new RedirectView();
		view.setAttributesMap(BeanUtil.toNonEmptyMap(req));
		view.setExposeModelAttributes(false); // false，post请求
		view.setUrl(payOrderVO.getReturnUrl());

		// return "redirect:" + payOrderVO.getReturnUrl();
		return view;
	}

}
